package ius.mantianx.controller;

import ius.mantianx.dao.DepartmentDao;
import ius.mantianx.dao.EmployeeDao;
import ius.mantianx.pojo.Department;
import ius.mantianx.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;
import java.util.Collection;

/**
 * @author starrysky
 * @title: EmployeeController
 * @projectName rev_thymeleaf_boot
 * @description: controller layer
 * @date 2021/2/813:03
 */
@Controller
public class EmployeeController {
    @Autowired
    private EmployeeDao employeeDao;
    @Autowired
    private DepartmentDao departmentDao;

    @GetMapping("/emps")
    public String emps(ModelMap modelMap) {
        Collection<Employee> all = employeeDao.getAll();
        modelMap.addAttribute("emps", all);
        return "emp/list";
    }

    @GetMapping("/goAddPage")
    public String goAddPage(ModelMap modelMap) {
        Collection<Department> departments = departmentDao.getDepartments();
        modelMap.addAttribute("departments", departments);
        return "emp/listAdd";
    }

    @PostMapping("/goemps")
    public String addEmp(Employee employee) {
        employeeDao.save(employee);
        return "redirect:/emps";
    }

    @GetMapping("/emp/{id}")
    public String toUpdateEmp(@PathVariable("id") Integer id, ModelMap modelMap) {
        Employee employee = employeeDao.employeeById(id);
        modelMap.addAttribute("emp", employee);
        Collection<Department> departments = departmentDao.getDepartments();
        modelMap.addAttribute("departments", departments);
        return "emp/update";
    }

    @PostMapping("/updateEmp")
    public String updateEmp(Employee employee) {
        employeeDao.save(employee);
        return "redirect:/emps";
    }

    @GetMapping("/deletemp/{id}")
    public String deletEmp(@PathVariable("id") Integer id) {
        employeeDao.delete(id);
        return "redirect:/emps";
    }

    @GetMapping("/user/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "login";
    }
}
